package org.example.syn;

import java.util.concurrent.CountDownLatch;

/**
 * @author Yyming
 * @version 10.0
 * Created by Yyming on 2020/10/29
 */
public class CountDownLatchTest {

    //资源1
    private static String resources1 = "";
    //资源2
    private static String resources2 = "";

    public static void main(String[] args) throws InterruptedException {
        //这里可以表示两个需要等待两个资源
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(() -> {
            resources1 = "初始化1";
            try {
                //模拟初始化等待
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        }).start();

        new Thread(() -> {
            resources2 = "初始化2";
            try {
                //模拟初始化等待
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        }).start();
        //阻塞等待CountDownLatch的技术减为0
        countDownLatch.await();
        //这里就可以保证资源都得到了初始化
        System.out.println(resources1 + resources2);
    }
}
